package cn.rocksolid.sport.common.ds.plugins;

import cn.rocksolid.sport.common.context.RockSolidContext;
import cn.rocksolid.sport.common.context.RockSolidContextHolder;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.function.Supplier;

@Component
public class AuditedMetaObjectHandler implements MetaObjectHandler {

  @Override
  public void insertFill(MetaObject metaObject) {
    RockSolidContext ctx = RockSolidContextHolder.getContextSafe();
    this.strictInsertFill(metaObject, "ct", String.class, ctx.getAccessType().name());
    this.strictInsertFill(metaObject, "cby", String.class, ctx.getAccessId());
    this.strictInsertFill(metaObject, "cdt", Date.class, new Date());
  }

  @Override
  public void updateFill(MetaObject metaObject) {
    RockSolidContext ctx = RockSolidContextHolder.getContextSafe();
    this.strictUpdateFill(metaObject, "mt", String.class, ctx.getAccessType().name());
    this.strictUpdateFill(metaObject, "mby", String.class, ctx.getAccessId());
    this.strictUpdateFill(metaObject, "mdt", Date.class, new Date());
  }

  @Override
  public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
    metaObject.setValue(fieldName, fieldVal.get());
    return this;
  }

}
